package com.example.weixinsystem.security.filter;

import com.example.weixinsystem.service.LoginService;
import com.weixin.common.core.exception.BaseException;
import com.weixin.common.core.form.LoginUserDetails;
import com.weixin.common.core.utils.JwtUtils;
import com.weixin.common.core.utils.SecurityUtil;
import com.weixin.common.core.utils.SpringBeanUtil;
import com.weixin.common.core.utils.TokenUtil;
import com.weixin.common.redis.service.RedisService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @version 1.0.0
 * @className: JwtAuthenticationTokenFilter
 * @description: token过滤器 验证token有效性
 * @author: zhangjunfa
 * @date: 2023/5/27 15:56
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private RedisService redisService;

    public JwtAuthenticationTokenFilter(RedisService redisService) {
        this.redisService = redisService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取Token
        String token = SecurityUtil.getToken(request);
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }

        //从redis中获取用户信息
        LoginUserDetails loginUser = redisService.getCacheObject(TokenUtil.getRedisCacheKey(token));
        if (Objects.isNull(loginUser)) {
            throw new BaseException("用户未登录");
        }
        // 刷新Token
        SpringBeanUtil.getBean(LoginService.class).refreshToken(request);

        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }


}
